<template>
  <div class="app-container">
    <div class="cardBox">
      <div style="display: flex" :gutter="10">
        <div style="flex: 1">
          <el-button
            @click="gobackWay"
            type="text"
            icon="el-icon-arrow-left"
            style="color: rgba(0, 0, 0, 0.85)"
            >返回</el-button
          >
          <el-divider direction="vertical"></el-divider>
          <span>{{ id ? "修改抽奖活动" : "添加抽奖活动" }}</span>
        </div>
      </div>
    </div>
    <div
      class="cardBox"
      v-loading="loading"
      style="height: calc(85vh - 80px); margin-top: 20px"
    >
      <div style="position: relative; display: flex">
        <div style="width: 900px">
          <el-scrollbar
            wrap-style="overflow-x:hidden;"
            style="height: calc(73vh - 80px)"
          >
            <el-form
              :model="basicForm"
              :rules="basicRules"
              ref="basicForm"
              label-width="150px"
              class="demo-ruleForm"
            >
              <el-col :span="23" class="splitTitle">
                <div class="split">活动信息</div>
              </el-col>
              <el-col :span="20">
                <el-form-item label="活动名称" prop="award_name">
                  <el-input
                    placeholder="请输入活动名称"
                    v-model="basicForm.award_name"
                    maxlength="20"
                    show-word-limit
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="20">
                <el-form-item label="时间段" prop="domeTime">
                  <el-date-picker
                    @change="domeTimeWay"
                    style="width: 100%"
                    value-format="yyyy-MM-dd"
                    v-model="domeTime"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="20">
                <el-form-item label="每人抽奖总次数" prop="user_lottery_num">
                  <el-input
                    placeholder="请输入每人抽奖总次数"
                    v-model="basicForm.user_lottery_num"
                    maxlength="5"
                    show-word-limit
                    onkeyup="value=value.replace(/\D/g,'')"
                  >
                    <template slot="append">
                      <el-popover placement="top-start" trigger="hover">
                        <p style="font-size: 12px">
                          用户可参与多少次抽奖,不填写则不限制次数
                        </p>
                        <el-button
                          slot="reference"
                          icon="el-icon-info"
                        ></el-button>
                      </el-popover>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="20">
                <el-form-item
                  label="每人每天抽奖总次数"
                  prop="user_days_lottery_num"
                >
                  <el-input
                    placeholder="请输入每人每天抽奖总次数"
                    v-model="basicForm.user_days_lottery_num"
                    maxlength="5"
                    show-word-limit
                    onkeyup="value=value.replace(/\D/g,'')"
                  >
                    <template slot="append">
                      <el-popover placement="top-start" trigger="hover">
                        <p style="font-size: 12px">
                          用户每天可参与多少次抽奖,不填写则不限制次数
                        </p>
                        <el-button
                          slot="reference"
                          icon="el-icon-info"
                        ></el-button>
                      </el-popover>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="20">
                <el-form-item label="用户限制" prop="user_type">
                  <el-radio-group v-model="basicForm.user_type">
                    <el-radio :label="0">不限制</el-radio>
                    <el-radio :label="1">指定用户可参加</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="20" v-if="basicForm.user_type == 1">
                <el-form-item label="指定用户" prop="user_ids">
                  <el-select
                    multiple
                    @change="user_idsWay"
                    v-model="user_ids"
                    style="width: 100%"
                    filterable
                    remote
                    clearable
                    reserve-keyword
                    placeholder="关键字查询(名称、ID、手机号)"
                    :remote-method="getUserListWay"
                    :loading="getSearchLoading"
                  >
                    <el-option
                      v-for="item in userList"
                      :key="item.id"
                      :label="
                        item.nickname +
                        '(' +
                        (item.mobile ? item.mobile : item.id) +
                        ')'
                      "
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="20">
                <el-form-item label="会员卡赠送次数" prop="is_use_cart_num">
                  <el-radio-group v-model="basicForm.is_use_cart_num">
                    <el-radio :label="0">不可用</el-radio>
                    <el-radio :label="1">可用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="20">
                <el-form-item label="签到赠送次数" prop="is_use_sign_num">
                  <el-radio-group v-model="basicForm.is_use_sign_num">
                    <el-radio :label="0">不可用</el-radio>
                    <el-radio :label="1">可用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :span="20">
                <el-form-item label="活动说明" prop="description">
                  <el-input
                    placeholder="请输入活动说明"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    v-model="basicForm.description"
                    maxlength="200"
                    show-word-limit
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-form>
          </el-scrollbar>
        </div>
        <!-- <div style="flex: 1"></div> -->
      </div>
      <div
        style="
          display: flex;
          justify-content: space-around;
          margin-top: 30px;
          text-align: center;
        "
      >
        <el-button type="primary" @click="submitWay">保存</el-button>
        <span></span>
        <!-- <el-button type="primary" @click="submitWay">保存</el-button> -->
      </div>
    </div>
  </div>
</template>

<script>
import { getUserList } from "@/api/user/index";
import { SaveAward, getAwardInfo } from "@/api/activity/index";
export default {
  data() {
    return {
      id: "",
      loading: false,
      userList: [],
      backupsForm: {},
      basicForm: {
        id: "",
        user_lottery_num: "",
        user_days_lottery_num: "",
        user_type: 0,
        user_ids: "",
        end_time: "",
        start_time: "",
        award_name: "",
        description: "",
        background_img: "",
        is_use_sign_num: 0,
        is_use_cart_num: 0,
      },
      domeTime: [],
      user_ids: [],
      getSearchLoading: false,
      basicRules: {
        award_name: [
          {
            required: true,
            validator: (rule, value, callback) => {
              let req = /[^0-9a-zA-Z\u4e00-\u9fa5]/g;
              if (!value) {
                callback(new Error("请输入活动名称"));
              } else {
                if (req.test(value)) {
                  callback(new Error("活动名称中不能存在特殊字符"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          },
        ],
        domeTime: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.domeTime.length == 0) {
                return callback(new Error("请选择活动的时间段"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        user_ids: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (this.basicForm.user_type !== 1) {
                callback();
              } else {
                if (this.user_ids.length == 0) {
                  return callback(new Error("请选择可参与的用户"));
                } else {
                  callback();
                }
              }
            },
            trigger: "change",
          },
        ],
        description: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error("请输入活动说明"));
              } else {
                callback();
              }
            },
            trigger: "change",
          },
        ],
        user_type: [
          {
            required: true,
            validator: (rule, value, callback) => {
              callback();
            },
            trigger: "change",
          },
        ],
        is_use_cart_num: [
          {
            required: true,
            validator: (rule, value, callback) => {
              callback();
            },
            trigger: "change",
          },
        ],
        is_use_sign_num: [
          {
            required: true,
            validator: (rule, value, callback) => {
              callback();
            },
            trigger: "change",
          },
        ],
      }, // 活动基本信息校验
    };
  },
  created() {
    this.loading = true;
    var _this = this;
    const p4 = new Promise((req, rej) => {
      getUserList({ search_name: "", search_type: 1, page: 1, count: 10 }).then(
        (res) => {
          if (res.code !== 200 || res.status !== 1) {
            _this.$messages.error(res.msg);
            rej();
            return;
          }
          _this.userList = res.data.list;
          req();
        }
      );
    });
    var arr = [];
    arr = [p4];
    if (_this.$route.query.id) {
      _this.id = _this.$route.query.id;
      const p8 = new Promise((req, rej) => {
        getAwardInfo({ id: _this.id }).then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            _this.$messages.error(res.msg);
            rej();
            return;
          }
          _this.backupsForm = res.data;
          req();
        });
      });
      arr = [p4, p8];
    }
    Promise.all(arr)
      .then(() => {
        if (_this.id) {
          _this.getBackupsForm();
        } else {
          _this.loading = false;
        }
      })
      .catch(() => {
        _this.loading = false;
      });
  },
  methods: {
    getBackupsForm() {
      this.basicForm.award_name = this.backupsForm.award_name;
      this.basicForm.id = this.backupsForm.id;
      this.basicForm.start_time = this.backupsForm.start_time;
      this.basicForm.end_time = this.backupsForm.end_time;
      this.domeTime = [this.backupsForm.start_time, this.backupsForm.end_time];
      this.basicForm.description = this.backupsForm.description;
      this.basicForm.user_type = this.backupsForm.user_type;
      this.basicForm.is_use_sign_num = this.backupsForm.is_use_sign_num;
      this.basicForm.is_use_cart_num = this.backupsForm.is_use_cart_num;
      if (this.backupsForm.user_lottery_num == 0) {
        this.basicForm.user_lottery_num = "";
      } else {
        this.basicForm.user_lottery_num = this.backupsForm.user_lottery_num;
      }
      if (this.backupsForm.user_days_lottery_num == 0) {
        this.basicForm.user_days_lottery_num = "";
      } else {
        this.basicForm.user_days_lottery_num =
          this.backupsForm.user_days_lottery_num;
      }
      this.user_ids = [];
      this.backupsForm.userList.forEach((item) => {
        this.user_ids.push(item.id);
      });
      this.userList.push(...this.backupsForm.userList);
      let forData = [];
      for (let i = 0; i < this.userList.length; i++) {
        if (!forData.some((e) => e.id == this.userList[i].id))
          forData.push(this.userList[i]);
      }
      this.userList = forData;
      this.user_idsWay(this.user_ids);
      this.loading = false;
    },
    // 返回本地团商品列表
    gobackWay() {
      this.$router.push("/activity/raffle");
    },
    submitWay() {
      var _this = this;
      _this.$refs.basicForm.validate((valid) => {
        if (valid) {
          _this.loading = true;
          SaveAward(_this.basicForm).then((res) => {
            if (res.code !== 200 || res.status !== 1) {
              _this.$messages.error(res.msg);
              _this.loading = false;
              return;
            }
            _this.gobackWay();
          });
        } else {
          return false;
        }
      });
    },
    domeTimeWay(val) {
      if (val.length !== 0) {
        this.basicForm.start_time = val[0];
        this.basicForm.end_time = val[1];
      } else {
        this.basicForm.start_time = "";
        this.basicForm.end_time = "";
      }
    },
    user_idsWay(val) {
      if (val.length !== 0) {
        this.basicForm.user_ids = val.toString();
      } else {
        this.basicForm.user_ids = "";
      }
    },
    getUserListWay(query) {
      this.getSearchLoading = true;
      getUserList({ search_name: query, search_type: 1 }).then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.$messages.error(res.msg);
          this.getSearchLoading = false;
          return;
        }
        this.userList = res.data.list;
        this.getSearchLoading = false;
      });
    },
  },
};
</script>

<style>
</style>